﻿using System;
using System.Net;
using System.Net.Mail;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using Besture.Common.Definition;
using Besture.Common.Helper;

namespace Besture.Common.Mail
{
    public class DevMailHelper
    {
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="mailMessage">邮件模型</param>
        public static void SendEmail(MailMessage mailMessage)
        {
            //发送邮箱信息
            string userName = AppSettings.GetDevEmailUserName();
            string password = AppSettings.GetDevEmailPassword();
            string host = AppSettings.GetDevEmailHost();
            int port = Convert.ToInt32(AppSettings.GetDevEmailPort());

            //如果未配置,直接跳过
            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(host) || port == 0)
                return;

            SmtpClient client = new SmtpClient(host, port)
            {
                //腾讯企业邮不允许使用安全链接 
                EnableSsl = true,
                UseDefaultCredentials = true,
                Credentials = new NetworkCredential(userName, password),
            };

            ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateCertificate);

            client.Send(mailMessage);
        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="to">收件人</param>
        /// <param name="subject">邮件主题</param>
        /// <param name="body">邮件内容</param>
        public static void SendEmail(string to, string subject, string body)
        {
            string userName = AppSettings.GetDevEmailUserName();
            string password = AppSettings.GetDevEmailPassword();
            string host = AppSettings.GetDevEmailHost();
            int port = Convert.ToInt32(AppSettings.GetDevEmailPort());
            //如果未配置,直接跳过
            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(host) || port == 0)
                return;
            SmtpClient client = new SmtpClient(host, port)
            {
                EnableSsl = false,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(userName, password),
                DeliveryMethod = SmtpDeliveryMethod.Network
            };
            var msg = new MailMessage(userName, to, subject, body) { BodyEncoding = System.Text.Encoding.UTF8, IsBodyHtml = true };
            client.Send(msg);
        }

        public static bool ValidateCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }

        /// <summary>
        /// 初始化邮件类[群发]
        /// </summary>
        /// <param name="subject">邮件主题</param>
        /// <param name="toMailArgs">收件地址数组</param>
        /// <param name="body">邮件内容</param>
        /// <param name="fileArgs">附件数组</param>
        /// <returns></returns>
        public MailMessage InitMailMessage(string subject, string[] toMailArgs, string body, string[] fileArgs)
        {
            MailMessage mailMessage = new MailMessage
                                          {Subject = subject, From = new MailAddress(AppSettings.GetDevEmailUserName())};
            //邮件主题
            //发件人
            //收件地址
            foreach (string t in toMailArgs)
            {
                mailMessage.To.Add(t);
            }
            mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
            mailMessage.IsBodyHtml = true;
            mailMessage.Body = body;
            //添加附件
            if (fileArgs != null && fileArgs.Length > 0)
            {
                foreach (string file in fileArgs)
                {
                    mailMessage.Attachments.Add(new Attachment(file));
                }
            }
            return mailMessage;
        }

        /// <summary>
        /// 初始化邮件类
        /// </summary>
        /// <param name="body">邮件内容</param>
        /// <param name="fileArgs">附件数组</param>
        /// <returns></returns>
        public static MailMessage InitMailMessage(string body, string[] fileArgs)
        {
            //邮件标题
            string subject = string.Format(@"【{0}】系统出现运行错误", AppSettings.GetSystemName());

            MailMessage mailMessage = new MailMessage
                                          {Subject = subject, From = new MailAddress(AppSettings.GetDevEmailUserName())};
            //收件地址
            string[] mailAddressArgs = AppSettings.GetDevDeveloperEmail().Split(',');
            for (int i = 0; i < mailAddressArgs.Length; i++)
            {
                if (!string.IsNullOrEmpty(mailAddressArgs[i]))
                {
                    mailMessage.To.Add(mailAddressArgs[i]);
                }
            }
            //邮件文字格式
            mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
            mailMessage.IsBodyHtml = true;
            //邮件主体

            var mailBodyTemplate = IoHelper.ReadFile(Constants.PATH_DEV_EMAIL_TEMPLATE);
            mailBodyTemplate = mailBodyTemplate.Replace("{SystemName}", AppSettings.GetSystemName());
            mailBodyTemplate = mailBodyTemplate.Replace("{Date}", DateTimeHelper.FormatStandard());
            mailBodyTemplate = mailBodyTemplate.Replace("{BugContent}", body);

            mailMessage.Body = mailBodyTemplate;

            //添加附件
            if (fileArgs != null && fileArgs.Length > 0)
            {
                foreach (string file in fileArgs)
                {
                    mailMessage.Attachments.Add(new Attachment(file));
                }
            }
            return mailMessage;
        }

    }
}
